package ca.cserkesz.healthform;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
 *
 * @author Laza Gyuri cst. <laza.gyuri@cserkesz.ca>
 */
public class PDFGenerator extends SwingWorker {
    
    private ArrayList<Scout> m_scoutList;
        
    private String m_campName;
    
    public PDFGenerator(ArrayList<Scout> sl) {
        m_scoutList = sl;
    }
    
    public void setCampName(String campName) {
        m_campName = campName;
    }
    
    private void drawText(String text, int x, int y, PDPageContentStream contentStream, int size) throws IOException {
        if (!text.isEmpty()) {
            contentStream.beginText();
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, size);
            contentStream.moveTextPositionByAmount(x, y);
            contentStream.setNonStrokingColor(Color.BLACK);
            contentStream.drawString(text);
            contentStream.endText();
        }
    }
    
    private void generateHealthFormPage1(Scout scout, PDPageContentStream contentStream) throws IOException, ParseException {
        
        
        
        
        drawText(scout.getTroopNumber(), 565, 720, contentStream, 12);
        drawText(m_campName, 530, 684, contentStream, 12);
        
        
        
        
        // Name
        drawText(scout.getLastName() + " " +
                 scout.getFirstName() + " " +
                 scout.getMiddleInitial(), 75, 634, contentStream, 12);
        
        // Date of Birth
        String [] dateOfBirth = scout.getDateOfBirth().split("/");
        if (dateOfBirth.length == 3) {
            drawText(dateOfBirth[0], 438, 634, contentStream, 12);
            drawText(dateOfBirth[1], 462, 634, contentStream, 12);
            drawText(dateOfBirth[2], 487, 634, contentStream, 12);
            Calendar now = Calendar.getInstance();
            int year = now.get(Calendar.YEAR);
            int age = year - Integer.parseInt(dateOfBirth[0]) - 1900;
            drawText(""+age, 538, 634, contentStream, 12);
        }        
        
        // Gender
        if (scout.getGender().toLowerCase().contentEquals("male")) {
            drawText("x", 76, 600, contentStream, 12);
        } else {
            drawText("x", 124, 600, contentStream, 12);
        }
        
        // Measurements
        drawText(scout.getHeight(), 210, 601, contentStream, 12);
        drawText(scout.getWeight(), 320, 601, contentStream, 12);
        
        // Address
        drawText(scout.getHomeAddress(), 105, 578, contentStream, 12);
        drawText(scout.getHomeApt(), 508, 578, contentStream, 12);
        drawText(scout.getHomeCity(), 55, 555, contentStream, 12);
        drawText(scout.getHomeProv(), 260, 555, contentStream, 12);
        drawText(scout.getHomePostalCode(), 325, 555, contentStream, 12);
        if (!scout.getHomePhone().isEmpty()) {
            String homeAreaCode = scout.getHomePhone().substring(0, 3);
            String homePhone1 = scout.getHomePhone().substring(3, 6);
            String homePhone2 = scout.getHomePhone().substring(6);
            drawText(homeAreaCode, 450, 555, contentStream, 10);
            drawText(homePhone1 + "-" + homePhone2, 471, 555, contentStream, 12);
        }
        
        
        
        
        drawText(scout.getEmergencyContact1Name(), 62, 499, contentStream, 12);
        drawText(scout.getEmergencyContact1Relationship(), 409, 499, contentStream, 12);
        if (!scout.getEmergencyContact1HomePhone().isEmpty()) {
            drawText(scout.getEmergencyContact1HomePhone().substring(0, 3), 102, 476, contentStream, 12);
            drawText(scout.getEmergencyContact1HomePhone().substring(3, 6) + "-" +
                     scout.getEmergencyContact1HomePhone().substring(6), 135, 476, contentStream, 12);
        }
        if (!scout.getEmergencyContact1WorkPhone().isEmpty()) {
            drawText(scout.getEmergencyContact1WorkPhone().substring(0, 3), 292, 476, contentStream, 12);
            drawText(scout.getEmergencyContact1WorkPhone().substring(3, 6) + "-" +
                     scout.getEmergencyContact1WorkPhone().substring(6), 325, 476, contentStream, 12);
        }
        if (!scout.getEmergencyContact1CellPhone().isEmpty()) {
            drawText(scout.getEmergencyContact1CellPhone().substring(0, 3), 465, 476, contentStream, 12);
            drawText(scout.getEmergencyContact1CellPhone().substring(3, 6) + "-" +
                     scout.getEmergencyContact1CellPhone().substring(6), 493, 476, contentStream, 12);
        }
        drawText(scout.getEmergencyContact1Address(), 73, 464, contentStream, 10);
        drawText(scout.getEmergencyContact2Name(), 62, 430, contentStream, 12);
        drawText(scout.getEmergencyContact2Relationship(), 409, 430, contentStream, 12);
        if (!scout.getEmergencyContact2HomePhone().isEmpty()) {
            drawText(scout.getEmergencyContact2HomePhone().substring(0, 3), 101, 407, contentStream, 12);
            drawText(scout.getEmergencyContact2HomePhone().substring(3, 6) + "-" +
                     scout.getEmergencyContact2HomePhone().substring(6), 135, 407, contentStream, 12);
        }
        if (!scout.getEmergencyContact2WorkPhone().isEmpty()) {
            drawText(scout.getEmergencyContact2WorkPhone().substring(0, 3), 291, 407, contentStream, 12);
            drawText(scout.getEmergencyContact2WorkPhone().substring(3, 6) + "-" +
                     scout.getEmergencyContact2WorkPhone().substring(6), 325, 407, contentStream, 12);
        }
        if (!scout.getEmergencyContact2CellPhone().isEmpty()) {
            drawText(scout.getEmergencyContact2CellPhone().substring(0, 3), 470, 407, contentStream, 12);
            drawText(scout.getEmergencyContact2CellPhone().substring(3, 6) + "-" +
                     scout.getEmergencyContact2CellPhone().substring(6), 497, 407, contentStream, 12);
        }
        drawText(scout.getEmergencyContact1Address(), 73, 395, contentStream, 10);
        
        
        
        
        
        drawText(scout.getInsuranceCompany(), 125, 353, contentStream, 12);
        drawText(scout.getInsuranceNumber(), 397, 353, contentStream, 12);
        drawText(scout.getInsuranceAddress(), 200, 330, contentStream, 12);
        drawText(scout.getInsuranceProv(), 267, 307, contentStream, 12);
        drawText(scout.getInsurancePostalCode(), 413, 307, contentStream, 12);
        if (!scout.getInsurancePhone().isEmpty()) {
            drawText(scout.getInsurancePhone().substring(0, 3), 160, 284, contentStream, 12);
            drawText(scout.getInsurancePhone().substring(3, 6) + "-" +
                     scout.getInsurancePhone().substring(6), 190, 284, contentStream, 12);
        }
        drawText(scout.getInsuranceHolder(), 415, 284, contentStream, 12);
        
        
        
        
        
        drawText(scout.getDoctorName(), 103, 242, contentStream, 12);
        if (!scout.getDoctorPhone().isEmpty()) {
            drawText(scout.getDoctorPhone().substring(0, 3), 390, 242, contentStream, 12);
            drawText(scout.getDoctorPhone().substring(3, 6) + "-" +
                     scout.getDoctorPhone().substring(6), 420, 242, contentStream, 12);
        }
        drawText(scout.getSpecialistName(), 115, 219, contentStream, 12);
        if (!scout.getSpecialistPhone().isEmpty()) {
            drawText(scout.getSpecialistPhone().substring(0, 3), 390, 219, contentStream, 12);
            drawText(scout.getSpecialistPhone().substring(3, 6) + "-" +
                     scout.getSpecialistPhone().substring(6), 420, 219, contentStream, 12);
        }
        if (!scout.getTreatment().isEmpty()) {
            drawText("x", 337, 207, contentStream, 12);
        } else {
            drawText("x", 404, 207, contentStream, 12);
        }
        drawText(scout.getTreatment(), 30, 172, contentStream, 12);
        
        
        
        
        String [] tetanus = scout.getTetanus().split("/");
        if (tetanus.length == 3) {
            drawText(tetanus[0], 70, 63, contentStream, 12);
            drawText(tetanus[1], 97, 63, contentStream, 12);
            drawText(tetanus[2], 123, 63, contentStream, 12);
        }
        String [] diphtheria = scout.getDiphtheria().split("/");
        if (diphtheria.length == 3) {
            drawText(diphtheria[0], 187, 63, contentStream, 12);
            drawText(diphtheria[1], 211, 63, contentStream, 12);
            drawText(diphtheria[2], 236, 63, contentStream, 12);
        }
        String [] polio = scout.getPolio().split("/");
        if (polio.length == 3) {
            drawText(polio[0], 279, 63, contentStream, 12);
            drawText(polio[1], 305, 63, contentStream, 12);
            drawText(polio[2], 333, 63, contentStream, 12);
        }
        String [] hepB = scout.getHepB().split("/");
        if (hepB.length == 3) {
            drawText(hepB[0], 408, 63, contentStream, 12);
            drawText(hepB[1], 428, 63, contentStream, 12);
            drawText(hepB[2], 449, 63, contentStream, 12);
        }
        String [] varicella = scout.getVaricella().split("/");
        if (varicella.length == 3) {
            drawText(varicella[0], 502, 63, contentStream, 12);
            drawText(varicella[1], 520, 63, contentStream, 12);
            drawText(varicella[2], 539, 63, contentStream, 12);
        }
        String [] measles = scout.getMeasles().split("/");
        if (measles.length == 3) {
            drawText(measles[0], 69, 42, contentStream, 12);
            drawText(measles[1], 94, 42, contentStream, 12);
            drawText(measles[2], 121, 42, contentStream, 12);
        }
        String [] mumps = scout.getMumps().split("/");
        if (mumps.length == 3) {
            drawText(mumps[0], 179, 42, contentStream, 12);
            drawText(mumps[1], 205, 42, contentStream, 12);
            drawText(mumps[2], 233, 42, contentStream, 12);
        }
        String [] rubella = scout.getRubella().split("/");
        if (rubella.length == 3) {
            drawText(rubella[0], 289, 42, contentStream, 12);
            drawText(rubella[1], 308, 42, contentStream, 12);
            drawText(rubella[2], 333, 42, contentStream, 12);
        }
        String [] influenzaB = scout.getInfluenzaB().split("/");
        if (influenzaB.length == 3) {
            drawText(influenzaB[0], 497, 42, contentStream, 12);
            drawText(influenzaB[1], 518, 42, contentStream, 12);
            drawText(influenzaB[2], 540, 42, contentStream, 12);
        }
        
    }
    
    private void generateHealthFormPage2(Scout scout, PDPageContentStream contentStream) throws IOException {
        
        if (!scout.getMedAllergies().isEmpty()) {
            drawText("x", 311, 728, contentStream, 12);
        } else {
            drawText("x", 345, 728, contentStream, 12);
        }
        drawText(scout.getMedAllergies(), 82, 705, contentStream, 10);
            
        if (!scout.getInsectAllergies().isEmpty()) {
            drawText("x", 218, 670, contentStream, 12);
            String [] insects = scout.getInsectAllergies().split("/");
            if (insects.length > 0) {
                drawText(insects[0], 291, 671, contentStream, 10);
            }
            if (insects.length > 1) {
                drawText(insects[1], 399, 671, contentStream, 10);
            }
        } else {
            drawText("x", 254, 670, contentStream, 12);
        }
        
        if (!scout.getAnimalAllergies().isEmpty()) {
            drawText("x", 218, 659, contentStream, 12);
            String [] animal = scout.getAnimalAllergies().split("/");
            if (animal.length > 0) {
                drawText(animal[0], 291, 660, contentStream, 10);
            }
            if (animal.length > 1) {
                drawText(animal[1], 399, 660, contentStream, 10);
            }
        } else {
            drawText("x", 254, 659, contentStream, 12);
        }
        
        if (!scout.getPlantAllergies().isEmpty()) {
            drawText("x", 218, 647, contentStream, 12);
            String [] plant = scout.getPlantAllergies().split("/");
            if (plant.length > 0) {
                drawText(plant[0], 291, 648, contentStream, 10);
            }
            if (plant.length > 1) {
                drawText(plant[1], 399, 648, contentStream, 10);
            }
        } else {
            drawText("x", 254, 647, contentStream, 12);
        }
        
        if (!scout.getFoodAllergies().isEmpty()) {
            drawText("x", 218, 636, contentStream, 12);
            String [] food = scout.getFoodAllergies().split("/");
            if (food.length > 0) {
                drawText(food[0], 291, 637, contentStream, 10);
            }
            if (food.length > 1) {
                drawText(food[1], 399, 637, contentStream, 10);
            }
        } else {
            drawText("x", 254, 636, contentStream, 12);
        }
        
        if (!scout.getOtherAllergies().isEmpty()) {
            drawText("x", 218, 624, contentStream, 12);
            String [] other = scout.getOtherAllergies().split("/");
            if (other.length > 0) {
                drawText(other[0], 291, 625, contentStream, 10);
            }
            if (other.length > 1) {
                drawText(other[1], 399, 625, contentStream, 10);
            }
        } else {
            drawText("x", 254, 624, contentStream, 12);
        }
        
        
        
        
        if (!scout.getInfectionIssues().isEmpty()) {
            drawText("x", 326, 538, contentStream, 12);
            String [] infect = scout.getInfectionIssues().split("/");
            if (infect.length > 0) {
                drawText(infect[0], 112, 527, contentStream, 10);
            }
            if (infect.length > 1) {
                drawText(infect[1], 436, 538, contentStream, 12);
            }
        } else {
            drawText("x", 363, 538, contentStream, 12);
        }
    
        if (!scout.getHeartIssues().isEmpty()) {
            drawText("x", 326, 504, contentStream, 12);
            String [] heart = scout.getHeartIssues().split("/");
            if (heart.length > 0) {
                drawText(heart[0], 112, 492, contentStream, 10);
            }
            if (heart.length > 1) {
                drawText(heart[1], 436, 504, contentStream, 12);
            }
        } else {
            drawText("x", 363, 504, contentStream, 12);
        }
        
        if (!scout.getBloodIssues().isEmpty()) {
            drawText("x", 326, 468, contentStream, 12);
            String [] blood = scout.getBloodIssues().split("/");
            if (blood.length > 0) {
                drawText(blood[0], 112, 458, contentStream, 10);
            }
            if (blood.length > 1) {
                drawText(blood[1], 436, 468, contentStream, 12);
            }
        } else {
            drawText("x", 363, 468, contentStream, 12);
        }
        
        if (!scout.getBreathingIssues().isEmpty()) {
            drawText("x", 326, 432, contentStream, 12);
            String [] breath = scout.getBreathingIssues().split("/");
            if (breath.length > 0) {
                drawText(breath[0], 112, 423, contentStream, 10);
            }
            if (breath.length > 1) {
                drawText(breath[1], 436, 432, contentStream, 12);
            }
        } else {
            drawText("x", 363, 432, contentStream, 12);
        }
    
        if (!scout.getNervousIssues().isEmpty()) {
            drawText("x", 326, 400, contentStream, 12);
            String [] nerv = scout.getNervousIssues().split("/");
            if (nerv.length > 0) {
                drawText(nerv[0], 112, 390, contentStream, 10);
            }
            if (nerv.length > 1) {
                drawText(nerv[1], 436, 400, contentStream, 12);
            }
        } else {
            drawText("x", 363, 400, contentStream, 12);
        }
    
        if (!scout.getMentalIssues().isEmpty()) {
            drawText("x", 326, 365, contentStream, 12);
            String [] mental = scout.getMentalIssues().split("/");
            if (mental.length > 0) {
                drawText(mental[0], 112, 353, contentStream, 10);
            }
            if (mental.length > 1) {
                drawText(mental[1], 436, 365, contentStream, 12);
            }
        } else {
            drawText("x", 363, 365, contentStream, 12);
        }
    
        if (!scout.getKidneyIssues().isEmpty()) {
            drawText("x", 326, 331, contentStream, 12);
            String [] kidney = scout.getKidneyIssues().split("/");
            if (kidney.length > 0) {
                drawText(kidney[0], 112, 320, contentStream, 10);
            }
            if (kidney.length > 1) {
                drawText(kidney[1], 436, 331, contentStream, 12);
            }
        } else {
            drawText("x", 363, 331, contentStream, 12);
        }
    
        if (!scout.getDigestionIssues().isEmpty()) {
            drawText("x", 326, 296, contentStream, 12);
            String [] digest = scout.getDigestionIssues().split("/");
            if (digest.length > 0) {
                drawText(digest[0], 112, 284, contentStream, 10);
            }
            if (digest.length > 1) {
                drawText(digest[1], 436, 296, contentStream, 12);
            }
        } else {
            drawText("x", 363, 296, contentStream, 12);
        }
    
        if (!scout.getHormonalIssues().isEmpty()) {
            drawText("x", 326, 261, contentStream, 12);
            String [] hormone = scout.getHormonalIssues().split("/");
            if (hormone.length > 0) {
                drawText(hormone[0], 112, 252, contentStream, 10);
            }
            if (hormone.length > 1) {
                drawText(hormone[1], 436, 261, contentStream, 12);
            }
        } else {
            drawText("x", 363, 261, contentStream, 12);
        }
        
        if (scout.getSwim().toLowerCase().contentEquals("yes")) {
            drawText("x", 255, 222, contentStream, 12);
        } else {
            drawText("x", 363, 222, contentStream, 12);
        }
        
        if (scout.getAbility().toLowerCase().contentEquals("beginner")) {
            drawText("x", 183, 208, contentStream, 12);
        } else if (scout.getAbility().toLowerCase().contentEquals("intermediate")) {
            drawText("x", 291, 208, contentStream, 12);
        } else if (scout.getAbility().toLowerCase().contentEquals("advanced")) {
            drawText("x", 435, 208, contentStream, 12);
        } else { //Non-swimmer
            drawText("x", 81, 208, contentStream, 12);
        }
        
        // Swimming certificate
        drawText(scout.getCert(), 206, 197, contentStream, 10);
        
        // Current date
        SimpleDateFormat date = new SimpleDateFormat("yy / MM / dd");
        Date now = Calendar.getInstance().getTime();
        drawText(date.format(now), 424, 13, contentStream, 12);
    }
    
    private void generateHealthFormPage3(Scout scout, PDPageContentStream contentStream) throws IOException {
        
        drawText(scout.getMeningitis(), 284, 497, contentStream, 12);
        
        // Current date
        SimpleDateFormat date = new SimpleDateFormat("yy / MM / dd");
        Date now = Calendar.getInstance().getTime();
        drawText(date.format(now), 394, 308, contentStream, 12);
        
        // Camper's Name
        drawText(scout.getLastName() + " " +
                 scout.getMiddleInitial() + " " +
                 scout.getFirstName(), 115, 245, contentStream, 12);
        
        // Date of Birth
        drawText(scout.getDateOfBirth(), 420, 245, contentStream, 12);
        
        // Mailing Address
        String addressLine1 = scout.getHomeAddress();
        if (!scout.getHomeApt().isEmpty()) {
            addressLine1 += " # " + scout.getHomeApt();
        }
        drawText(addressLine1, 115, 217, contentStream, 12);
        drawText(scout.getHomeCity() + ", " +
                 scout.getHomeProv() + ", " +
                 scout.getHomePostalCode(), 115, 190, contentStream, 12);
    }
    
    @Override
    public Object doInBackground() {
        
        
        try {
            PDDocument template = PDDocument.load("camp_health_form_2011_.pdf");
            PDPage templatePage1 = (PDPage)template.getDocumentCatalog().getAllPages().get(0);
            PDPage templatePage2 = (PDPage)template.getDocumentCatalog().getAllPages().get(1);

            PDDocument template2 = PDDocument.load("meningitis_vaccination_form_2011_.pdf");
            PDPage templatePage3 = (PDPage)template2.getDocumentCatalog().getAllPages().get(0);
            
            PDDocument document = new PDDocument();
            
            int progress = 0;
            for (Scout scout : m_scoutList) {
                progress++;
                
                // Page 1
                PDPage page1 = document.importPage(templatePage1);
                PDPageContentStream contentStreamPage1 = new PDPageContentStream(document, page1, true, true);
                generateHealthFormPage1(scout, contentStreamPage1);
                //drawGridLines(contentStreamPage1);
                contentStreamPage1.close();
                
                // Page 2
                PDPage page2 = document.importPage(templatePage2);
                PDPageContentStream contentStreamPage2 = new PDPageContentStream(document, page2, true, true);
                generateHealthFormPage2(scout, contentStreamPage2);
                contentStreamPage2.close();
                
                // Page 3
                PDPage page3 = document.importPage(templatePage3);
                PDPageContentStream contentStreamPage3 = new PDPageContentStream(document, page3, true, true);
                generateHealthFormPage3(scout, contentStreamPage3);
                contentStreamPage3.close();
                
                setProgress(progress * 100 / m_scoutList.size());
            }

            // Save
            JFileChooser openDialog = new JFileChooser();
            openDialog.setFileFilter(new FileNameExtensionFilter("PDF fájl fajta", "pdf"));
            openDialog.showSaveDialog(null);
            File pdfFile = openDialog.getSelectedFile();
            if (pdfFile != null) {
                document.save(pdfFile.getAbsolutePath());
            }
            document.close();
            if (pdfFile != null) {
                System.exit(0);
            }

        } catch (Exception ex) {
            Logger.getLogger(HealthFormController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;       
    }
    
}

